import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { DisposalRecord, DisposalRecordQuery, DisposalStats } from '@/types/disposal'

// 分页信息接口
interface Pagination {
  current: number
  size: number
  total: number
}

// 模拟投放记录数据
const mockDisposalRecords: DisposalRecord[] = [
  {
    id: 1,
    deviceCode: 'DLF-001',
    wasteType: 'paper',
    deviceLocation: '北京市朝阳区建国路88号',
    userPhone: '13800138001',
    disposalWeight: 2.5,
    disposalAmount: 12.5,
    disposalPhoto: 'https://via.placeholder.com/300x200?text=投放照片',
    disposalTime: '2024-01-15 09:30:25',
    createdAt: '2024-01-15 09:30:25',
    updatedAt: '2024-01-15 09:30:25'
  },
  {
    id: 2,
    deviceCode: 'DLF-002',
    wasteType: 'textile',
    deviceLocation: '上海市浦东新区陆家嘴环路1000号',
    userPhone: '13800138002',
    disposalWeight: 1.8,
    disposalAmount: 9.0,
    disposalPhoto: 'https://via.placeholder.com/300x200?text=投放照片',
    disposalTime: '2024-01-15 10:15:30',
    createdAt: '2024-01-15 10:15:30',
    updatedAt: '2024-01-15 10:15:30'
  },
  {
    id: 3,
    deviceCode: 'DLF-003',
    wasteType: 'mixed',
    deviceLocation: '广州市天河区体育西路189号',
    userPhone: '13800138003',
    disposalWeight: 3.2,
    disposalAmount: 16.0,
    disposalPhoto: 'https://via.placeholder.com/300x200?text=投放照片',
    disposalTime: '2024-01-15 11:20:15',
    createdAt: '2024-01-15 11:20:15',
    updatedAt: '2024-01-15 11:20:15'
  },
  {
    id: 4,
    deviceCode: 'DLF-001',
    wasteType: 'paper',
    deviceLocation: '北京市朝阳区建国路88号',
    userPhone: '13800138004',
    disposalWeight: 1.5,
    disposalAmount: 7.5,
    disposalTime: '2024-01-15 14:45:20',
    createdAt: '2024-01-15 14:45:20',
    updatedAt: '2024-01-15 14:45:20'
  },
  {
    id: 5,
    deviceCode: 'DLF-004',
    wasteType: 'textile',
    deviceLocation: '深圳市南山区科技园南区',
    userPhone: '13800138005',
    disposalWeight: 2.8,
    disposalAmount: 14.0,
    disposalPhoto: 'https://via.placeholder.com/300x200?text=投放照片',
    disposalTime: '2024-01-15 16:30:45',
    createdAt: '2024-01-15 16:30:45',
    updatedAt: '2024-01-15 16:30:45'
  },
  {
    id: 6,
    deviceCode: 'DLF-002',
    wasteType: 'mixed',
    deviceLocation: '上海市浦东新区陆家嘴环路1000号',
    userPhone: '13800138006',
    disposalWeight: 4.1,
    disposalAmount: 20.5,
    disposalPhoto: 'https://via.placeholder.com/300x200?text=投放照片',
    disposalTime: '2024-01-15 18:15:30',
    createdAt: '2024-01-15 18:15:30',
    updatedAt: '2024-01-15 18:15:30'
  },
  {
    id: 7,
    deviceCode: 'DLF-003',
    wasteType: 'paper',
    deviceLocation: '广州市天河区体育西路189号',
    userPhone: '13800138007',
    disposalWeight: 2.2,
    disposalAmount: 11.0,
    disposalTime: '2024-01-16 08:45:10',
    createdAt: '2024-01-16 08:45:10',
    updatedAt: '2024-01-16 08:45:10'
  },
  {
    id: 8,
    deviceCode: 'DLF-005',
    wasteType: 'textile',
    deviceLocation: '杭州市西湖区文三路398号',
    userPhone: '13800138008',
    disposalWeight: 1.9,
    disposalAmount: 9.5,
    disposalPhoto: 'https://via.placeholder.com/300x200?text=投放照片',
    disposalTime: '2024-01-16 10:20:35',
    createdAt: '2024-01-16 10:20:35',
    updatedAt: '2024-01-16 10:20:35'
  },
  {
    id: 9,
    deviceCode: 'DLF-001',
    wasteType: 'mixed',
    deviceLocation: '北京市朝阳区建国路88号',
    userPhone: '13800138009',
    disposalWeight: 3.5,
    disposalAmount: 17.5,
    disposalPhoto: 'https://via.placeholder.com/300x200?text=投放照片',
    disposalTime: '2024-01-16 13:15:20',
    createdAt: '2024-01-16 13:15:20',
    updatedAt: '2024-01-16 13:15:20'
  },
  {
    id: 10,
    deviceCode: 'DLF-004',
    wasteType: 'paper',
    deviceLocation: '深圳市南山区科技园南区',
    userPhone: '13800138010',
    disposalWeight: 2.1,
    disposalAmount: 10.5,
    disposalTime: '2024-01-16 15:40:55',
    createdAt: '2024-01-16 15:40:55',
    updatedAt: '2024-01-16 15:40:55'
  }
]

// 模拟投放统计
const mockDisposalStats: DisposalStats = {
  totalRecords: 1568,
  totalWeight: 3256.8,
  totalAmount: 16284.0,
  todayRecords: 23,
  todayWeight: 48.5,
  todayAmount: 242.5
}

export const useDisposalRecords = () => {
  const loading = ref(false)
  const exporting = ref(false)

  // 搜索表单
  const searchForm = reactive<DisposalRecordQuery>({
    deviceCode: '',
    userPhone: '',
    deviceLocation: '',
    wasteType: undefined,
    dateRange: [],
    page: 1,
    size: 10
  })

  // 分页信息
  const pagination = reactive<Pagination>({
    current: 1,
    size: 10,
    total: 0
  })

  // 投放统计
  const disposalStats = ref<DisposalStats>(mockDisposalStats)

  // 投放记录列表
  const disposalList = ref<DisposalRecord[]>([])

  // 获取回收类型标签样式
  const getWasteTypeTag = (type: string) => {
    switch (type) {
      case 'paper': return 'primary'
      case 'textile': return 'success'
      case 'mixed': return 'warning'
      default: return 'info'
    }
  }

  // 获取回收类型文本
  const getWasteTypeText = (type: string) => {
    switch (type) {
      case 'paper': return '纸壳类'
      case 'textile': return '织物类'
      case 'mixed': return '混合类'
      default: return type
    }
  }

  // 加载投放记录列表
  const loadDisposalRecords = async () => {
    loading.value = true
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500))

      // 模拟数据过滤
      let filteredData = [...mockDisposalRecords]

      if (searchForm.deviceCode) {
        filteredData = filteredData.filter(item =>
          item.deviceCode.includes(searchForm.deviceCode!)
        )
      }

      if (searchForm.userPhone) {
        filteredData = filteredData.filter(item =>
          item.userPhone.includes(searchForm.userPhone!)
        )
      }

      if (searchForm.deviceLocation) {
        filteredData = filteredData.filter(item =>
          item.deviceLocation.includes(searchForm.deviceLocation!)
        )
      }

      if (searchForm.wasteType) {
        filteredData = filteredData.filter(item =>
          item.wasteType === searchForm.wasteType
        )
      }

      if (searchForm.dateRange && searchForm.dateRange.length === 2) {
        const [startDate, endDate] = searchForm.dateRange
        filteredData = filteredData.filter(item => {
          const disposalDate = item.disposalTime.split(' ')[0]
          return disposalDate >= startDate && disposalDate <= endDate
        })
      }

      // 模拟分页
      const startIndex = (pagination.current - 1) * pagination.size
      const endIndex = startIndex + pagination.size
      const pagedData = filteredData.slice(startIndex, endIndex)

      disposalList.value = pagedData
      pagination.total = filteredData.length

    } catch (error) {
      ElMessage.error('获取投放记录失败')
      console.error('获取投放记录失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 搜索处理
  const handleSearch = () => {
    pagination.current = 1
    loadDisposalRecords()
  }

  // 重置搜索
  const handleReset = () => {
    Object.assign(searchForm, {
      deviceCode: '',
      userPhone: '',
      deviceLocation: '',
      wasteType: undefined,
      dateRange: [],
      page: 1,
      size: 10
    })
    pagination.current = 1
    loadDisposalRecords()
  }

  // 分页改变
  const handlePageChange = (page: number) => {
    pagination.current = page
    loadDisposalRecords()
  }

  // 每页大小改变
  const handleSizeChange = (size: number) => {
    pagination.size = size
    pagination.current = 1
    loadDisposalRecords()
  }

  // 批量导出
  const handleExport = async () => {
    try {
      exporting.value = true

      // 模拟导出确认
      await ElMessageBox.confirm(
        '确定要导出投放记录数据吗？',
        '导出确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      // 模拟导出处理
      await new Promise(resolve => setTimeout(resolve, 1000))

      // 构建导出参数
      const exportParams = {
        deviceCode: searchForm.deviceCode,
        userPhone: searchForm.userPhone,
        deviceLocation: searchForm.deviceLocation,
        wasteType: searchForm.wasteType,
        startTime: searchForm.dateRange?.[0],
        endTime: searchForm.dateRange?.[1]
      }

      console.log('导出参数:', exportParams)

      // 模拟导出成功
      ElMessage.success('导出任务已提交，文件生成后将自动下载')

      // 模拟文件下载
      setTimeout(() => {
        const blob = new Blob(['投放记录导出数据'], { type: 'application/vnd.ms-excel' })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `投放记录_${new Date().toISOString().split('T')[0]}.xlsx`
        a.click()
        URL.revokeObjectURL(url)
      }, 2000)

    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('导出失败')
        console.error('导出失败:', error)
      }
    } finally {
      exporting.value = false
    }
  }

  // 编辑投放记录
  const handleEdit = (row: DisposalRecord) => {
    ElMessage.info(`编辑投放记录: ${row.deviceCode}`)
    // TODO: 实现编辑逻辑
  }

  // 删除投放记录
  const handleDelete = (row: DisposalRecord) => {
    ElMessageBox.confirm(
      `确定要删除设备 ${row.deviceCode} 的投放记录吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      ElMessage.success('删除成功')
      // TODO: 实现删除逻辑
    }).catch(() => {
      ElMessage.info('已取消删除')
    })
  }

  // 组件挂载时加载数据
  onMounted(() => {
    loadDisposalRecords()
  })

  return {
    loading,
    exporting,
    searchForm,
    pagination,
    disposalStats,
    disposalList,
    getWasteTypeTag,
    getWasteTypeText,
    loadDisposalRecords,
    handleSearch,
    handleReset,
    handlePageChange,
    handleSizeChange,
    handleExport,
    handleEdit,
    handleDelete
  }
}
